from custom.handlers.basehandler import BaseRequestHandler
from utils.wechat import check_wx_signature, parse_wx_msg, receive, replay
from utils.wechat.kf_replay import KfTextMessage, KfMusicMessage, KfNewsMessage
from utils.qq_music import get_song_key, query_music, download_file, get_album_thumb
from settings.config import config
from models.tables import MusicModel
from sqlalchemy.exc import OperationalError
import requests
import os
import json
import time
from requests import urllib3
urllib3.disable_warnings()


class WechatHandler(BaseRequestHandler):
    def get(self, *args, **kwargs):
        timestamp = self.get_argument('timestamp', '')
        nonce = self.get_argument('nonce', '')
        signature = self.get_argument('signature', '')
        echostr = self.get_argument('echostr', '')
        if check_wx_signature(config.WeChatConfig.Token, timestamp, nonce, signature):
            print(1)
            self.write(echostr)
        else:
            print(2)
            self.write('error')

    def post(self, *args, **kwargs):
        rec_msg = parse_wx_msg(self.request.body)
        if isinstance(rec_msg, receive.TextMessage):
            self.write('')
            from_user = rec_msg.FromUserName
            result = query_music(rec_msg.Content)
            keyword = rec_msg.Content
            db_result = self.handle_query_result(result, keyword)
            if len(db_result) == 0:
                kf_replay_msg = KfTextMessage(from_user, '我找不到你想要的，555')
                self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())
                return
            news_info = {
                'articles': db_result
            }
            print(db_result)
            kf_replay_msg = KfNewsMessage(from_user, news_info)
            # kf_replay_msg = KfMusicMessage(from_user, music_info)
            self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())
            return

        if isinstance(rec_msg, receive.TextMessage):
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            title = '风雨无阻'
            desc = '风雨无阻 desc'
            music_url = 'http://isure.stream.qqmusic.qq.com/C4000025GslA2cMgqe.m4a?vkey=C5376EF80730DF0767C58CF54D5112FFD0A604EB95156E9F37D71344F6F2591FBC63974655288F292043DA7E1CED2A7ADE83DCE08274E11F&guid=6501846271&uin=979358990&fromtag=66'
            hq_url = 'http://isure.stream.qqmusic.qq.com/C4000025GslA2cMgqe.m4a?vkey=C5376EF80730DF0767C58CF54D5112FFD0A604EB95156E9F37D71344F6F2591FBC63974655288F292043DA7E1CED2A7ADE83DCE08274E11F&guid=6501846271&uin=979358990&fromtag=66'
            thumb = 'N1oQMwupTlRuKRzyIj70e8cIhasK0p7lMH89NDuuuQo'
            replay_msg = replay.MusicMessage(to_user=to_user, from_user=from_user, title=title,
                                             desc=desc, music_url=music_url, hq_url=hq_url, thumb=thumb)
            self.write(replay_msg.send())
            return
        if isinstance(rec_msg, receive.TextMessage):
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            content = 'replay:' + rec_msg.Content
            replay_msg = replay.TextMessage(to_user=to_user, from_user=from_user, content=content)
            self.write(replay_msg.send())
        elif isinstance(rec_msg, receive.ImageMessage):
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            media = rec_msg.MediaId
            replay_msg = replay.ImageMessage(to_user=to_user, from_user=from_user, media_id=media)
            self.write(replay_msg.send())
        elif isinstance(rec_msg, receive.VoiceMessage):
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            media_id = 'N1oQMwupTlRuKRzyIj70e7-SfYQtMnMqXn0pyx3ElWE'
            replay_msg = replay.VoiceMessage(to_user=to_user, from_user=from_user, media_id=media_id)
            self.write(replay_msg.send())
        else:
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            content = '我不知道你发的是什么...'
            replay_msg = replay.TextMessage(to_user=to_user, from_user=from_user, content=content)
            self.write(replay_msg.send())

    def handle_db_song(self, db_song):
        diff = int(2.9 * 24 * 60 * 60)
        if int(time.time()) - int(db_song.thumb_time) > diff:
            '''
            thumb_media_id 过期
            '''
            thumb_file = os.path.join(config.APP_ROOT, db_song.my_thumb_url)
            print('thumb_file', thumb_file)
            new_media_id = self.wx_token_manager.upload_material('thumb', thumb_file)
            db_song.thumb_time = int(time.time())
            db_song.thumb_media_id = new_media_id
            try:
                self.db.commit()
            except OperationalError:
                self.db.rollback()

    def handle_no_song_in_db(self, **kwargs):
        keyword = kwargs.get('keyword')
        song = kwargs.get('song', dict())
        song_mid = song.get('song_mid')
        album_mid = song.get('album_mid')
        song_name = song.get('song_name')
        song_desc = song.get('song_desc')
        singer_name = song.get('singer_name')
        song_key = get_song_key(song_mid)
        # print('song_key', song_key)
        song_url = None
        if len(song_key.get('url')) > 0 and len(song_key.get('sip')) > 0:
            song_url = song_key.get('sip')[0] + song_key.get('url')[0]
            # print('song_url', song_url)
        if song_url:
            song_file = download_file('audio', song_url)
            # print('song_file', song_file)
        thumb_url = get_album_thumb(album_mid)
        thumb_file = download_file('image', thumb_url)
        # print('thumb_file', thumb_file)
        thumb_media_id = self.wx_token_manager.upload_material('thumb', thumb_file.get('full_path'))
        music = MusicModel(keyword=keyword,
                           song_name=song_name,
                           song_desc=song_desc,
                           singer_name=singer_name,
                           song_mid=song_mid,
                           album_id=album_mid,
                           song_url=song_url,
                           my_song_url=song_file.get('server_path'),
                           thumb_url=thumb_url,
                           my_thumb_url=thumb_file.get('server_path'),
                           thumb_media_id=thumb_media_id,
                           thumb_time=str(int(time.time())))
        self.db.add(music)
        try:
            self.db.commit()
        except OperationalError:
            self.db.rollback()
        return music

    def handle_query_result(self, result_list, keyword):
        db_result = list()
        if len(result_list) == 0:
            return db_result
        for _ in result_list:
            song_mid = _.get('song_mid', '')
            album_mid = _.get('album_id', '')
            db_song = self.db.query(MusicModel).filter_by(song_mid=song_mid).first()
            need_commit = False
            if db_song:
                db_result.append({
                    "title": db_song.song_name + '-' + db_song.singer_name,
                    "description": db_song.song_desc or db_song.song_name,
                    "url": config.DOMAIN + 'music/index?song_mid=' + song_mid,
                    "picurl": config.DOMAIN + db_song.my_thumb_url
                })
            else:
                need_commit = True
                thumb_url = get_album_thumb(album_mid)
                thumb_file = download_file('image', thumb_url)
                music = MusicModel(keyword=keyword,
                                   song_id=_.get('song_id', ''),
                                   song_name=_.get('song_name', ''),
                                   song_desc=_.get('song_desc', ''),
                                   singer_name=_.get('singer_name', ''),
                                   song_mid=_.get('song_mid', ''),
                                   album_id=_.get('album_id', ''),
                                   song_url='',
                                   my_song_url='',
                                   thumb_url=thumb_url,
                                   my_thumb_url=thumb_file.get('server_path'),
                                   thumb_media_id='',
                                   thumb_time=str(int(time.time())))
                self.db.add(music)
                db_result.append({
                    "title": _.get('song_name', '') + '-' + _.get('singer_name', ''),
                    "description": _.get('song_desc', '') or _.get('song_name', ''),
                    "url": config.DOMAIN + 'music/index?song_mid=' + song_mid,
                    "picurl": config.DOMAIN + thumb_file.get('server_path')
                })
        if need_commit:
            self.db.commit()
        return db_result